package com.study.zgw.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
@Slf4j
public class AioFileChannel {
    public static void main(String[] args) {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("src/data.txt"), StandardOpenOption.READ)) {
            /**
             * 参数1 ByteBuffer
             * 参数2 读取的起始位置
             * 参数3 附件
             * 参数4 回调对象
             */
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.info("------read begin-----");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override // 读取完成
                public void completed(Integer result, ByteBuffer attachment) {
                    log.info("读取到数据大小：{}",result);
                    attachment.flip();// 切换成读模式
                    String bufferReult = Charset.defaultCharset().decode(attachment).toString();
                    log.info("读取到数据：{}",bufferReult);
                }

                @Override // 读取失败
                public void failed(Throwable exc, ByteBuffer attachment) {
                    log.error("读取失败",exc.getMessage(),exc);
                }
            });
            System.in.read();
            log.info("------read end-------");
        } catch (IOException e) {
            log.error("错误：{}",e.getMessage(),e);
        }

    }

}
